package com.group.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.group.entity.CommonResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("myAccessDeniedHandler")
public class MyAccessDeniedHandler implements AccessDeniedHandler {
 
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException, IOException {
        // 跨域处理
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的请求方法
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        // 允许的请求头
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 设置响应头
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //通过httpServletRepsonse返回给前台
        //ObjectMapper类的writeValueString方法，是springboot中的jackson提供的将类或其他对象转换成json格式的方法
        httpServletResponse.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.error(403,"权限不足")));
 
    }
}